import React, { useState } from 'react';
import { Button, Form, Input, message } from 'antd'; // 引入 Ant Design 组件
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
import './LoginPage.css';

function LoginPage() {
  const navigate = useNavigate();
  const [form] = Form.useForm();

  const handleSubmit = async (values) => {

    try {
      const response = await axios.post('http://127.0.0.1:8080/auth/login', values);
      console.log(response);
      if(response.status === 200){
            var data = response.data;
            if(data.code === 0){
                navigate('/welcome'); // 登录成功后跳转到主页面
            }else{
                message.error(data.msg || '登录失败，请检查用户名和密码。');
            }
      }else{
        message.error('网络错误');
      }
    } catch (error) {
        message.error(error.data.msg || '登录失败，请检查用户名和密码。');
    }
  };

  return (
      <div className="login-page">
        <Form
          form={form}
          name="login-form"
          onFinish={handleSubmit}
          labelCol={{ span: 8 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600 }}
        >
          <Form.Item
            label="用户名"
            name="username"
            rules={[{ required: true, message: '请输入用户名!' }]}
          >
            <Input />
          </Form.Item>

          <Form.Item
            label="密码"
            name="password"
            rules={[{ required: true, message: '请输入密码!' }]}
          >
            <Input.Password />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
            <Button type="primary" htmlType="submit">
              登录
            </Button>
          </Form.Item>
        </Form>
      </div>
    );
}

export default LoginPage;